package com.econ.powercloud.ems.job;

import com.econ.powercloud.ems.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Author : zjf
 * @Description : 定时任务执行操作的入口
 * 被定时任务线程池调用，用来执行指定bean里面的方法
 * @Date : 2023/8/10 10:48
 * @Modified by : zjf
 */
@Slf4j
public class SchedulingRunnable implements Runnable{

    /**
     * spring中的bean名称
     */
    private String beanName;

    /**
     * 方法名
     */
    private String methodName;

    /**
     * 定时控制主键id
     */
    private Integer schedulePid;

    public SchedulingRunnable(String beanName, String methodName) {
        this(beanName, methodName, null);
    }

    public SchedulingRunnable(String beanName, String methodName, Integer schedulePid) {
        this.beanName = beanName;
        this.methodName = methodName;
        this.schedulePid = schedulePid;
    }

    @Override
    public void run() {
        try {
            Object target = SpringContextUtil.getBean(beanName);
            Method method = null;
            if (schedulePid != null) {
                method = target.getClass().getDeclaredMethod(methodName, Integer.class);
            } else {
                method = target.getClass().getDeclaredMethod(methodName);
            }
            ReflectionUtils.makeAccessible(method);
            if (schedulePid != null) {
                method.invoke(target, schedulePid);
            } else {
                method.invoke(target);
            }
        } catch (Exception ex) {
            log.error(String.format("定时任务执行异常 - bean：%s，方法：%s，参数：%s ", beanName, methodName, schedulePid), ex);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SchedulingRunnable that = (SchedulingRunnable) o;
        if (schedulePid == null) {
            return beanName.equals(that.beanName) &&
                    methodName.equals(that.methodName) &&
                    that.schedulePid == null;
        }

        return beanName.equals(that.beanName) &&
                methodName.equals(that.methodName) &&
                schedulePid.equals(that.schedulePid);
    }

    @Override
    public int hashCode() {
        if (schedulePid == null) {
            return Objects.hash(beanName, methodName);
        }

        return Objects.hash(beanName, methodName, schedulePid);
    }

}
